package cn.opencodes.framework.core.datasources;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 动态数据源
 * @author HJ
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
	private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public DynamicDataSource(DataSource defaultTargetDataSource, Map<String, DataSource> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(new HashMap<>(targetDataSources));
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSource();
    }
    
    /**
     * 设置当前线程数据源
     * @param dataSource 数据源名称
     */
    public static void setDataSource(String dataSource) {
    	contextHolder.set(dataSource);
    }
    /**
     * 获得当前线程数据源
     */
    public static String getDataSource() {
    	return contextHolder.get();
    }
    /**
     * 清空当前线程数据源
     */
    public static void clearDataSource() {
    	contextHolder.remove();
    }

}
